<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="folderId = ''"
  >
    <BasicForm @register="registerForm">
      <template #code="{ model }">
        <a-input
          v-model:value="model.code"
          placeholder="请输入物料编码"
          :readonly="model.isSysCodeBoolean"
        />
      </template>
      <template #isSysCodeBoolean="{ model }">
        <a-checkbox v-model:checked="model.isSysCodeBoolean" @change="handleSysChange">
          用系统编号
        </a-checkbox>
      </template>
      <template #imgUpload>
        <Upload v-model:value="folderId" listType="picture" />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import Upload from '/@/components/Form/src/components/Upload.vue';
  import {
    getMaterialListInfo,
    updateMaterialList,
    addMaterialList,
    getMaterialCode,
  } from '/@/api/erp/material/list';
  import { getUnitList } from '/@/api/erp/unit/list';
  import { getPropertylList } from '/@/api/erp/material/property';
  import { getCategoryList } from '/@/api/erp/material/category';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'code',
      label: '物料编码',
      component: 'Input',
      slot: 'code',
      rules: [
        {
          required: true,
          validator: (_, value) => {
            if (getFieldsValue().isSysCodeBoolean) return Promise.resolve();
            if (value === '') {
              return Promise.reject('请输入物料编码');
            } else if (!/^[0-9a-zA-Z_]{6,15}$/.test(value)) {
              return Promise.reject('请输入由6-15位的数字、字母、下划线组成的字符串');
            } else {
              return Promise.resolve();
            }
          },
        },
      ],
      colProps: { span: 18 },
    },
    {
      field: 'isSysCodeBoolean',
      label: '',
      component: 'Input',
      slot: 'isSysCodeBoolean',
      required: true,
      colProps: { span: 5, offset: 1 },
    },
    {
      field: 'name',
      label: '物料名称',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入物料名称',
      },
    },
    {
      field: 'model',
      label: '规格型号',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入规格型号',
      },
    },
    {
      field: 'unitId',
      label: '单位',
      component: 'ApiSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择单位',
        api: getUnitList,
        labelField: 'name',
        valueField: 'id',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'classesId',
      label: '物料类别',
      component: 'ApiSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择物料类别',
        api: getCategoryList,
        labelField: 'typeName',
        valueField: 'id',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'propertyId',
      label: '物料属性',
      component: 'ApiSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择物料属性',
        api: getPropertylList,
        labelField: 'propertyName',
        valueField: 'id',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'fileId',
      label: '图片上传',
      component: 'Upload',
      slot: 'imgUpload',
      colProps: { span: 24 },
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const folderId = ref('');

  const emit = defineEmits(['success']);

  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: FormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getMaterialListInfo(data.id);
      folderId.value = record.fileId;
      setFieldsValue({
        ...record,
      });
    } else {
      folderId.value = '';
      const materialCode = await getMaterialCode();
      setFieldsValue({ code: materialCode, isSysCodeBoolean: true });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增物料' : '编辑物料'));

  const handleSysChange = async (e) => {
    let materialCode = '';
    if (e.target.checked) {
      materialCode = await getMaterialCode();
    }
    setFieldsValue({ code: materialCode });
  };

  const handleSubmit = async () => {
    try {
      setFieldsValue({ fileId: folderId.value });
      const values = await validate();
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addMaterialList(values);
        notification.success({
          message: '新增物料',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateMaterialList(values);
        notification.success({
          message: '编辑物料',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };
</script>
